package com.globant.rdm.iod.guice;


import org.apache.log4j.Logger;

import com.globant.rdm.iod.DomainObjectInjector;
import com.globant.rdm.iod.EntityFactory;
import com.google.inject.Inject;

public class GuiceAwareEntityFactory implements EntityFactory {

	private final DomainObjectInjector domainObjectInjector;

	private static final Logger logger = Logger.getLogger(GuiceAwareEntityFactory.class);
	
	@Inject
	public GuiceAwareEntityFactory(final DomainObjectInjector domainObjectInjector) {
		super();
		this.domainObjectInjector = domainObjectInjector;
	}

	@Override
	public <T> T buildEntity(final Class<T> entityCLass) {
		final T instance = createInstance(entityCLass);
		logger.debug("Resolving dependencies for " + entityCLass);
		domainObjectInjector.resolveDependencies(instance);
		return instance;
	}

	private <T> T createInstance(final Class<T> entityCLass) {
		try {
			logger.debug("Creating new instance of " + entityCLass);
			return entityCLass.newInstance();
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

}
